<template>
  <v-app>
    <Topbar @onBack="clearForm" @onSaveBtnClick="addReceiveAddress" />
    <v-content class="grey lighten-3">
      <InputBlock label="姓名" v-model="form.name" />
      <v-divider></v-divider>
      <InputBlock label="手机号码" v-model="form.tel" />
      <v-divider></v-divider>
      <InputBlock label="邮政编码" v-model="form.postCode" />
      <v-divider></v-divider>
      <InputBlock label="所在地区" v-model="dist" type="dist" />
      <v-divider></v-divider>
      <InputBlock label="详细地址" v-model="form.detailAddress" />
      <v-divider></v-divider>
      <v-overlay :value="showOverlay">
        <v-progress-circular indeterminate size="64"></v-progress-circular>
      </v-overlay>
      <v-snackbar bottom color="info" :timeout="2000" v-model="showMessage">
        信息填写不完整
      </v-snackbar>
    </v-content>
  </v-app>
</template>

<script>
import Topbar from './components/Topbar.vue';
import InputBlock from '@/components/InputBlock.vue';
import request from '@/request/index';

export default {
  components: { Topbar, InputBlock },
  data() {
    return {
      showOverlay: false,
      showMessage: false
    };
  },
  mounted() {
    const id = this.$route.query.id;
    if (id) {
      request.get(`/userReceiveAddress/${id}`).then(resp => {
        this.$store.commit('saveCurrReceiveAddressForm', resp);
      });
    }
  },
  methods: {
    clearForm() {
      const id = this.$route.query.id;
      if (id) {
        this.$store.commit('clearCurrReceiveAddressForm');
      }
    },
    addReceiveAddress() {
      for (const key of Object.keys(this.form)) {
        if (this.form[key] === '') {
          this.showMessage = true;
          return;
        }
      }
      this.showOverlay = true;
      const id = this.$route.query.id;
      if (id) {
        request
          .put(`/userReceiveAddress/${id}`, {
            ...this.form,
            ...this.$store.state.currPickDist
          })
          .then(() => {
            this.showOverlay = false;
            this.$store.commit('clearCurrReceiveAddressForm');
            this.$router.push('/addresses');
          });
      } else {
        request
          .post('/userReceiveAddress', {
            ...this.form,
            appUserId: this.$store.state.currentUser.id
          })
          .then(() => {
            this.showOverlay = false;
            this.$store.commit('clearCurrReceiveAddressForm');
            this.$router.push('/addresses');
          });
      }
    }
  },
  computed: {
    form() {
      return this.$store.state.currReceiveAddressForm;
    },
    dist() {
      const id = this.$route.query.id;
      const _form =
        id && this.$store.state.currPickDist
          ? this.$store.state.currPickDist
          : this.form;
      return _form.province + _form.city + _form.region;
    }
  },
  watch: {
    $route() {
      this.$store.commit('saveCurrReceiveAddressForm', this.form);
    }
  }
};
</script>
